package com.mt.repair.service.repairManagement.impl;

import com.mt.repair.dao.repairManagement.DeviceCatUserDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.repair.entity.repairManagement.DeviceCatUser;
import com.mt.repair.service.repairManagement.DeviceCatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class DeviceCatUserServiceBean extends BaseService implements DeviceCatUserService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private DeviceCatUserDao deviceCatUserDao;

	@Resource
	private RedisTemplate<String, List<DeviceCatUser>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询设备用户关联表集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findDeviceCatUsers(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindDeviceCatUsers(pageDTO);
		List<DeviceCatUser> deviceCatUserDTOS = this.deviceCatUserDao.findDeviceCatUsers(pageDTO);
		Long totalCount = this.deviceCatUserDao.findDeviceCatUserTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(deviceCatUserDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部设备用户关联表集合
	 *
	 */
	@Override
	public List<DeviceCatUser> findAllDeviceCatUsers(){
		return this.deviceCatUserDao.findAllDeviceCatUsers();
	}

	/**
	 * 查询所有设备用户关联表集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<DeviceCatUser> findAllDeviceCatUsersWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllDeviceCatUsersWithIdName();
		return this.deviceCatUserDao.findAllDeviceCatUsersWithIdName();
	}

	/**
	 * 根据名称查询设备用户关联表集合(只提取ID 和 Name)
	 *
	 * @param deviceCatUserName 名称
	 */
	@Override
	public List<DeviceCatUser> findDeviceCatUsersWithIdNameByName(String deviceCatUserName){
		//TODO:请在此校验参数的合法性
		this.validateFindDeviceCatUsersWithIdNameByName(deviceCatUserName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:DeviceCatUser_where_deviceCatUserName_" + deviceCatUserName);
		List<DeviceCatUser> deviceCatUsers = new ArrayList<>();
		if (keys.isEmpty()) {
		deviceCatUsers = this.deviceCatUserDao.findDeviceCatUsersWithIdNameByName(deviceCatUserName);
		redisTemplate.opsForValue().set("searchData:DeviceCatUser_where_deviceCatUserName_" + deviceCatUserName, deviceCatUsers, 30, TimeUnit.DAYS);
		} else {
		deviceCatUsers = redisTemplate.opsForValue().get("searchData:DeviceCatUser_where_deviceCatUserName_" + deviceCatUserName);
		}
		return deviceCatUsers;
	}

	/**
	 * 根据ID查询指定的设备用户关联表(只提取ID 和 Name)
	 *
	 * @param deviceCatUserId Id
	 */
	@Override
	public DeviceCatUser findDeviceCatUsersWithIdNameById(Long deviceCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateFindDeviceCatUsersWithIdNameById(deviceCatUserId);
		return this.deviceCatUserDao.findDeviceCatUsersWithIdNameById(deviceCatUserId);
	}

	/**
	 * 根据ID查询指定的设备用户关联表
	 *
	 * @param deviceCatUserId Id
	 */
	@Override
	public DeviceCatUser findDeviceCatUser(Long deviceCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateFindDeviceCatUser(deviceCatUserId);
		return this.deviceCatUserDao.findDeviceCatUser(deviceCatUserId);
	}

	/**
	 * 根据ID查询指定的设备用户关联表(包含外键)
	 *
	 * @param deviceCatUserId Id
	 */
	@Override
	public DeviceCatUser findDeviceCatUserWithForeignName(Long deviceCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateFindDeviceCatUserWithForeignName(deviceCatUserId);
		return this.deviceCatUserDao.findDeviceCatUserWithForeignName(deviceCatUserId);
	}

	/**
	 * 新增设备用户关联表
	 *
	 * @param deviceCatUser 实体对象
	 */
	@Override
	public DeviceCatUser saveDeviceCatUser(DeviceCatUser deviceCatUser){
		//TODO:请在此校验参数的合法性
		this.validateSaveDeviceCatUser(deviceCatUser);
		//TODO:填充公共参数
		this.setSavePulicColumns(deviceCatUser);
		//校验当前用户是否已经绑定
		Long count=this.deviceCatUserDao.findDeviceCatUserByUserAndDevice(deviceCatUser.getUserId(),deviceCatUser.getDeviceId());
		if(count>0){
			String error = "新增保存设备用户关联表出错，当前用户已经管理该设备，如需增加管理时长，请修改 ";
			throw new BusinessException(error);
		}
		Long rows = this.deviceCatUserDao.saveDeviceCatUser(deviceCatUser);
		if(rows != 1)
		{
			String error = "新增保存设备用户关联表出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return deviceCatUser;
	}

	/**
	 * 更新设备用户关联表
	 *
	 * @param deviceCatUser 实体对象
	 */
	@Override
	public DeviceCatUser updateDeviceCatUser(DeviceCatUser deviceCatUser){
		//TODO:请在此校验参数的合法性
		this.validateUpdateDeviceCatUser(deviceCatUser);
		Long rows = this.deviceCatUserDao.updateDeviceCatUser(deviceCatUser);
		if(rows != 1)
		{
			String error = "修改保存设备用户关联表出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return deviceCatUser;
	}

	/**
	 * 根据ID删除设备用户关联表
	 *
	 * @param deviceCatUserId ID
	 */
	@Override
	public void deleteDeviceCatUser(Long deviceCatUserId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteDeviceCatUser(deviceCatUserId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(DeviceCatUser.class, deviceCatUserId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.deviceCatUserDao.deleteDeviceCatUser(deviceCatUserId);
		if(rows != 1){
			String error = "删除设备用户关联表出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindDeviceCatUsers(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	private void validateFindDeviceCatUsersWithIdNameByName(String deviceCatUserName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}


	private void validateFindAllDeviceCatUsersWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	private void validateFindDeviceCatUsersWithIdNameById(Long deviceCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	private void validateFindDeviceCatUser(Long deviceCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	private void validateFindDeviceCatUserWithForeignName(Long deviceCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	private void validateSaveDeviceCatUser(DeviceCatUser deviceCatUser) {
	//不为空判断
	if (deviceCatUser.getEid() != null || deviceCatUser.getCreatorId() != null || deviceCatUser.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	private void validateUpdateDeviceCatUser(DeviceCatUser deviceCatUser) {
	//不为空判断
	if (deviceCatUser.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.deviceCatUserDao.findDeviceCatUserTotalCount(PageDTO.create(DeviceCatUser.FIELD_ID, deviceCatUser.getEid())) == 0) {
	throw new BusinessException("修改的设备用户关联表 " + deviceCatUser.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	private void validateDeleteDeviceCatUser(Long deviceCatUserId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateDeviceCatUser()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
